package demo.hadoop.tsdb;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * <li>Only the following characters are allowed: a to z, A to Z, 0 to 9, -, _,
 * ., / or Unicode letters (as per the specification)
 */
public class TSDBDecodeUtil implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1700552535291610208L;
    private static Map<String, Character> decodeMap = new HashMap<String, Character>();

    static {
        Map<Character, String> encodeMap = TSDBEncodeUtil.getEncodeMap();
        for (Character key : encodeMap.keySet()) {
            decodeMap.put(encodeMap.get(key), key);
        }
    }

    public static String decode(String s) {
        if (StringUtils.isBlank(s))
            return s;
        for (String key : decodeMap.keySet()) {
            s = StringUtils.replace(s, key, String.valueOf(decodeMap.get(key)));
        }
        return s;
    }

    public static Map<String, String> decodeMap(Map<String, String> tags) {
        if (tags == null)
            return tags;
        Map<String, String> resultMap = new HashMap<String, String>();
        Iterator<Map.Entry<String, String>> iterator = tags.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            String newValue = entry.getValue();
            for (String key : decodeMap.keySet()) {
                newValue = StringUtils.replace(newValue, key, String.valueOf(decodeMap.get(key)));
            }
            resultMap.put(entry.getKey(), newValue);
        }
        return resultMap;
    }

    private static String decodeLogIdentity(String value)
    // AsciiToString
    {
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split("-");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    public static void main(String[] args) {
        String a = "//A//124//B//";
        String b = "/brand_friend_coupon/$mark<[^/]+>";
        System.out.println();
        System.out.println(decode(a));
        System.out.println(decodeLogIdentity("64,49,50,52,58"));
    }

}
